<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>WebSocket聊天应用</title>
    <style>
        * {
            box-sizing: border-box;
            margin: 0;
            padding: 0;
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
        }
        
        body {
            background-color: #f0f2f5;
            padding: 20px;
        }
        
        .chat-container {
            max-width: 800px;
            margin: 0 auto;
            background-color: white;
            border-radius: 10px;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
            overflow: hidden;
        }
        
        .chat-header {
            background-color: #007bff;
            color: white;
            padding: 15px;
            text-align: center;
            font-size: 1.2rem;
        }
        
        .chat-messages {
            height: 500px;
            overflow-y: auto;
            padding: 20px;
            display: flex;
            flex-direction: column;
            gap: 15px;
        }
        
        .message {
            max-width: 70%;
            padding: 10px 15px;
            border-radius: 20px;
            word-wrap: break-word;
        }
        
        .message.sent {
            background-color: #007bff;
            color: white;
            align-self: flex-end;
        }
        
        .message.received {
            background-color: #e9ecef;
            color: #333;
            align-self: flex-start;
        }
        
        .message-system {
            color: #666;
            font-style: italic;
            align-self: center;
            font-size: 0.9rem;
        }
        
        .chat-input {
            display: flex;
            padding: 20px;
            border-top: 1px solid #eee;
        }
        
        #messageInput {
            flex: 1;
            padding: 12px 15px;
            border: 1px solid #ddd;
            border-radius: 25px;
            font-size: 1rem;
            outline: none;
            transition: border-color 0.3s;
        }
        
        #messageInput:focus {
            border-color: #007bff;
        }
        
        #sendButton {
            margin-left: 10px;
            padding: 12px 25px;
            background-color: #007bff;
            color: white;
            border: none;
            border-radius: 25px;
            cursor: pointer;
            font-size: 1rem;
            transition: background-color 0.3s;
        }
        
        #sendButton:hover {
            background-color: #0056b3;
        }
        
        #status {
            text-align: center;
            color: #666;
            padding: 10px;
            font-size: 0.9rem;
        }
    </style>
</head>
<body>
    <div class="chat-container">
        <div class="chat-header">WebSocket聊天应用</div>
        <div id="status">连接中...</div>
        <div class="chat-messages" id="messageList"></div>
        <div class="chat-input">
            <input type="text" id="messageInput" placeholder="输入消息...">
            <button id="sendButton">发送</button>
        </div>
    </div>

    <script>
        // DOM元素
        const messageInput = document.getElementById('messageInput');
        const sendButton = document.getElementById('sendButton');
        const messageList = document.getElementById('messageList');
        const statusElement = document.getElementById('status');
        
        // WebSocket连接
        let socket;
        let isConnected = false;
        
        // 初始化WebSocket连接
        function initWebSocket() {
            // 关闭可能存在的旧连接
            if (socket) {
                socket.close();
            }
            
            // 创建新连接
            socket = new WebSocket('ws://localhost:8080');
            
            // 连接建立
            socket.onopen = function() {
                isConnected = true;
                statusElement.textContent = '已连接，可开始聊天';
                addMessage('成功连接到聊天服务器', 'system');
                sendButton.disabled = false;
            };
            
            // 接收消息
            socket.onmessage = function(event) {
                // 确保消息是字符串格式
                let message = event.data;
                
                // 如果是Blob类型，转换为字符串
                if (event.data instanceof Blob) {
                    const reader = new FileReader();
                    reader.onload = function() {
                        addMessage(reader.result, 'received');
                    };
                    reader.readAsText(event.data);
                } else {
                    addMessage(message, 'received');
                }
            };
            
            // 连接关闭
            socket.onclose = function() {
                isConnected = false;
                statusElement.textContent = '连接已关闭，正在尝试重连...';
                addMessage('与服务器的连接已关闭', 'system');
                sendButton.disabled = true;
                
                // 自动重连
                setTimeout(initWebSocket, 3000);
            };
            
            // 连接错误
            socket.onerror = function(error) {
                statusElement.textContent = '连接错误';
                addMessage('连接发生错误: ' + error, 'system');
            };
        }
        
        // 添加消息到界面
        function addMessage(text, type) {
            const messageElement = document.createElement('div');
            messageElement.className = `message ${type}`;
            messageElement.textContent = text;
            messageList.appendChild(messageElement);
            
            // 滚动到底部
            messageList.scrollTop = messageList.scrollHeight;
        }
        
        // 发送消息
        function sendMessage() {
            const message = messageInput.value.trim();
            if (!message || !isConnected) return;
            
            // 发送消息
            socket.send(message);
            
            // 在本地显示发送的消息
            addMessage(message, 'sent');
            
            // 清空输入框
            messageInput.value = '';
        }
        
        // 事件监听
        sendButton.addEventListener('click', sendMessage);
        
        // 按Enter发送消息
        messageInput.addEventListener('keypress', function(e) {
            if (e.key === 'Enter') {
                sendMessage();
            }
        });
        
        // 初始化连接
        initWebSocket();
    </script>
</body>
</html>
